package com.hmdp.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.hmdp.entity.ShopType;
import com.hmdp.mapper.ShopTypeMapper;
import com.hmdp.service.IShopTypeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Set;

import static com.hmdp.utils.RedisConstants.CACHE_SHOP_TYPE_KEY;


@Service
public class ShopTypeServiceImpl extends ServiceImpl<ShopTypeMapper, ShopType> implements IShopTypeService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public List<ShopType> queryTypeList() {
        String key = CACHE_SHOP_TYPE_KEY;
        //查询缓存
        String jsonStr = stringRedisTemplate.opsForValue().get(key);
        List<ShopType> typeList = null;

        if (StrUtil.isNotBlank(jsonStr)) {
            typeList = JSONUtil.toList(jsonStr, ShopType.class);
            return typeList;
        }
        //缓存为空 查询数据库
        typeList = this.query().orderByAsc("sort").list();
        //查询为空，
        if (typeList == null) {
            return null;
        }
        //添加到缓存
        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(typeList));
        return typeList;
    }
}
